package com.xjx.account.controller;

import com.google.code.kaptcha.Producer;
import com.xjx.account.controller.request.AccountRegisterRequest;
import com.xjx.account.service.AccountService;
import com.xjx.common.enums.BizCodeEnum;
import com.xjx.common.enums.SendCodeEnum;
import com.xjx.common.util.CheckUtil;
import com.xjx.common.util.CommonUtil;
import com.xjx.common.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import com.xjx.account.controller.request.SendCodeRequest;
import com.xjx.account.controller.request.SendEmailCodeRequest;
import com.xjx.account.service.NotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    private static final Logger logger = LoggerFactory.getLogger(NotifyController.class);

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AccountService accountService;

    /**
     * 验证码过期时间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 1000 * 10 *  60;

    /**
     * 生成验证码
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){

        String captchaText = captchaProducer.createText();
        log.info("验证码内容:{}",captchaText);

        //存储redis,配置过期时间 ， jedis/lettuce
        redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,CAPTCHA_CODE_EXPIRED,TimeUnit.MILLISECONDS);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        try (ServletOutputStream outputStream = response.getOutputStream()){

            ImageIO.write(bufferedImage,"jpg",outputStream);
            outputStream.flush();

        } catch (IOException e) {
            log.error("获取流出错:{}",e.getMessage());
        }

    }

    private String getCaptchaKey(HttpServletRequest request){

        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "account-service:captcha:"+CommonUtil.MD5(ip+userAgent);
        log.info("验证码key:{}",key);
        return key;
    }

    /**
     * 发送短信验证码
     * @return
     */
    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request){

        String key = getCaptchaKey(request);

        String cacheCaptcha = redisTemplate.opsForValue().get(key);

        String captcha = sendCodeRequest.getCaptcha();

        if(captcha!=null && cacheCaptcha !=null && cacheCaptcha.equalsIgnoreCase(captcha)){
            //成功
            redisTemplate.delete(key);
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER,sendCodeRequest.getTo());
            return jsonData;
        }else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }

    }

    /**
     * 发送邮件验证码
     * @param sendEmailCodeRequest 发送邮件验证码请求
     * @return 发送结果
     */
    @PostMapping("/send_email_code")
    public JsonData sendEmailCode(@RequestBody SendEmailCodeRequest sendEmailCodeRequest) {
        
        // 参数校验
        if (sendEmailCodeRequest.getEmail() == null || sendEmailCodeRequest.getEmail().trim().isEmpty()) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        
        if (sendEmailCodeRequest.getType() == null || sendEmailCodeRequest.getType().trim().isEmpty()) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        
        // 邮箱格式校验
        if (!CheckUtil.isEmail(sendEmailCodeRequest.getEmail())) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        
        log.info("发送邮件验证码，邮箱: {}, 类型: {}", sendEmailCodeRequest.getEmail(), sendEmailCodeRequest.getType());
        
        try {
            // 调用NotifyService的sendEmailCode方法
            boolean success = notifyService.sendEmailCode(sendEmailCodeRequest.getEmail(), sendEmailCodeRequest.getType());
            
            if (success) {
                log.info("邮件验证码发送成功，邮箱: {}", sendEmailCodeRequest.getEmail());
                return JsonData.buildSuccess("邮件验证码发送成功");
            } else {
                log.error("邮件验证码发送失败，邮箱: {}", sendEmailCodeRequest.getEmail());
                return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
            }
        } catch (Exception e) {
            log.error("发送邮件验证码异常，邮箱: {}", sendEmailCodeRequest.getEmail(), e);
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(
            @RequestBody(required = false) Map<String, String> registerRequest,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String username) {

        // 优先使用URL参数，如果没有则使用请求体
        if (registerRequest != null) {
            if (email == null) email = registerRequest.get("email");
            if (password == null) password = registerRequest.get("password");
            if (code == null) code = registerRequest.get("code");
            if (username == null) username = registerRequest.get("username");
        }

        if (email == null || password == null || code == null) {
            return ResponseEntity.badRequest().body(Map.of("code", 400, "message", "邮箱、密码和验证码不能为空"));
        }

        logger.info("用户一步式注册，邮箱: {}", email);

        // 验证验证码
        String cachedCode = notifyService.getEmailCode(email, "register");
        if (cachedCode == null || !cachedCode.equals(code)) {
            return ResponseEntity.status(400).body(Map.of("code", 400, "message", "验证码错误或已过期"));
        }

        // 创建用户
        AccountRegisterRequest user = new AccountRegisterRequest();
        user.setMail(email);
        user.setUsername(email); // 使用邮箱作为用户名
        user.setPwd(password); // 未加密的密码，在service层会加密
        user.setUsername(username != null ? username : "用户" + email.substring(0, email.indexOf("@")));

        // 调用服务层方法创建用户
        JsonData registerResult = accountService.register(user);

        // 验证码验证成功后，删除缓存中的验证码
        if (registerResult.getCode() == 0) {
            notifyService.removeEmailCode(email, "register");
        }

        return ResponseEntity.status(registerResult.getCode() == 0 ? 200 : 400).body(registerResult);
    }

}

